<?php
namespace app\api\controller;

class VehicleIncomeExpense extends Permission
{   
    /**
     * 车辆开支表，包含每一次收入（应收）和支出，求和之后减去车辆收购价就是车辆的利润。减去欠款之后就是车辆实际利润 
     * status 
     * 0 待付款、待审核
     * 20 已完成
     * 90 未收到
     * */
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = [
            'is_void' => 1 //有效的
        ];

        if( isset($this->input_data['status']) && $this->input_data['status'] != 99999999 ) $map['a.status'] = $this->input_data['status'];
        if( isset($this->input_data['cate']) && $this->input_data['cate'] != '不限' ) $map['a.cate'] = $this->input_data['cate'];

        if( $this->post('is_rebate') != '' ) $map['a.is_rebate'] = $this->input_data['is_rebate'];
        if( $this->post('cate_id') > 0 ) $map['a.cate_id'] = $this->input_data['cate_id'];
        if( $this->post('io_type') != '不限' ) $map['a.io_type'] = $this->input_data['io_type'];

        if(isset($this->input_data['company']) && $this->input_data['company'] != '') $map['company'] = ['LIKE','%'.$this->input_data['company'].'%'];

        if(isset($this->input_data['vehicle_id']) && $this->input_data['vehicle_id'] != 0) $map['vehicle_id'] = $this->input_data['vehicle_id'];

        if(isset($this->input_data['plate_number']) && $this->input_data['plate_number'] !== '') $map['plate_number'] = ['LIKE','%'.$this->input_data['plate_number'].'%'];

        if($this->post('area_id') > 0)
        {
            $map['area_id'] = $this->post('area_id');
        }
        else
        {
            $map['area_id'] = ['IN',$this->myAllAreaIds];
        }

        if($this->post('belongs_month') != '')
        {
            // =========================
            // # 计算提交上来的时间范围
            // =========================
            $ym        = trim($this->post('belongs_month'));
            $startDate = strtotime($ym . '-01 00:00:00');
            $endDate   = strtotime('+1 month', $startDate);
            $map['belongs_date'] = ['BETWEEN',[$startDate,$endDate]];
        }


        $total = db('VehicleIncomeExpense')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->where($map)->count();
        $rows = db('VehicleIncomeExpense')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number')->order('id', 'desc')->page($page,$limit)->where($map)->select();
        $sql = db()->getLastSql();
        $list = [];
        foreach ($rows as $v) {
            $statusText = $this->_formatStatus($v);
            $v['statusText'] = $statusText['text'];
            $v['statusType'] = $statusText['type'];
            $v['amountClass'] = $v['io_type'] == '收入' ? 'red' : 'green';
            $v['Amount'] = $v['io_type'] == '收入' ? formatMoneyShow($v['amount']) : formatMoneyShow($v['amount'] * -1);
            $v['amount'] = formatMoneyShow($v['amount']);
            $v['createTime'] = date('m-d H:s',$v['create_time']);
            $v['create_time'] = date('Y-m-d H:s',$v['create_time']);
            $v['rejectTime'] = date('m-d H:s',$v['reject_time']);
            $v['pay_time'] = $v['status'] == 0 ? '未付款' : date('Y-m-d H:s',$v['pay_time']);
            $v['belongs_date'] = $v['belongs_date'] == 0 ? '无' : date('Y-m-d',$v['belongs_date']);
            $list[] = $v;
        }
        
        $data = [
            'total' => $total,
            'list' => $list,
            'map' => $map,
            'sql' => $sql
        ];
        $this->resSuc($data);
    }

    private function _formatStatus($v)
    {
        $type[0] = 'info';
        $type[20] = 'success';
        $type[90] = 'danger';

        $text[0] = $v['io_type'] == '支出' ? '待付款' : '待审核';
        $text[20] = '已完成';
        $text[90] = '未通过';

        $data = [
            'type' => $type[$v['status']],
            'text' => $text[$v['status']]
        ];

        return $data;
    }

    public function del()
    {
        $map = [
            'id' => $this->input_data['id'],
            'status' => 20
        ];
        if(db('VehicleIncomeExpense')->where( $map )->find()) $this->resErr('无法删除已完成的收支记录');
        db('VehicleIncomeExpense')->delete( $this->input_data['id']);
        
        $this->resSuc('ok');
    }
    public function invalid()
    {
        $map = [
            'id' => $this->input_data['id'],
            'status' => 20
        ];
        if(db('VehicleIncomeExpense')->where( $map )->find()) $this->resErr('无法作废已完成的收支记录');


        db('VehicleIncomeExpense')->where(['id'=>$this->post('id')])->update( ['is_void'=>0]);
        
        $this->resSuc('ok');
    }

    public function update()
    {
        $data['create_mode'] = '手动录入';
        $data['amount'] = formatMoneySave($this->input_data['amount']);
        $data['io_type'] = $this->input_data['io_type'];
        $data['belongs_date'] = strtotime( $this->input_data['belongs_date'] );
        $data['images'] = $this->input_data['images'];
        $data['vehicle_id'] = $this->input_data['vehicle_id'];
        $data['cate_id'] = $this->post('cate_id');
        $data['cate'] = db('VehicleIncomeExpenseCate')->where(['id'=>$this->post('cate_id')])->value('title');
        $data['cate_id'] = $this->input_data['cate_id'];
        $data['remark'] = $this->input_data['remark'];
        $data['status'] = 0; // 添加、编辑状态默认是0，重新提交也要设置状态为0

        $data['create_user'] = $this->user['realname'];
        $data['create_user_id'] = $this->user['id'];
        $data['create_time'] = time();


        if($this->input_data['id'] > 0)
        {
            $data['id'] = $this->input_data['id'];
            db('VehicleIncomeExpense')->update($data);
        }
        else
        {
            $id = db('VehicleIncomeExpense')->insertGetId($data);
        }

        $this->resSuc('success');
    }

    public function getById()
    {
        $map['id'] = $this->input_data['id'];
        $result = db('VehicleIncomeExpense')->where($map)->find();
        $this->resSuc($result);
    }

    // 审核通过支出和收入通用
    public function pay()
    {
        $list = json_decode($this->input_data['list'],true);
        $names = [];
        $price = 0;
        foreach ($list as $v) {
            $names[] = $v['plate_number'];
            $price = bcadd($price, $v['amount']);
        }

        $names = implode(',', $names);
        $type = $list[0]['io_type'];
        $amount = $type == '支出' ? formatMoneySave($price * -1) : formatMoneySave($price);
        # 创建付款记录
        $data = [
            'cate' => '车辆收支',
            'type' => $type,
            'relation_id' => 0,
            'relation_name' => $names,
            'amount' => $amount,
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time()
        ];
        // 支出就上传新的图片
        if($type == '支出'){
            $data['relation_id'] = $list[0]['id'];
            $data['images'] = $this->input_data['images'];
        }
        else
        {
            // 收入就用提交上来的图片
            $data['images'] = $list[0]['images'];
        }

        $pay_record_id = db('PayRecord')->insertGetId($data);


        # 更新“车辆收支表的”信息
        # pay_user 支出的话表示谁付的款，收入的话表示谁审核的 pay_time记录的是操作时间 belongs_date记录的是填写的付款是就
        foreach ($list as $v) {

            $oData = [
                'id' => $v['id']
            ];
            if($type == '支出') $oData['pay_images'] = $this->input_data['images'];
            
            // $oData['belongs_date'] = strtotime($this->post('belongs_date'));
            $oData['pay_user'] = $this->user['realname'];
            $oData['pay_user_id'] = $this->user['id'];
            $oData['pay_time'] = time();
            if($type == '支出') $oData['belongs_date'] = strtotime($this->post('belongs_date'));
            $oData['pay_record_id'] = $pay_record_id;
            $oData['status'] = 20;

            db('VehicleIncomeExpense')->update($oData);

            # 更新车辆利润
            action('common/Vehicle/updateProfit',['vehicleId'=>$v['vehicle_id']]);
        }



        $this->resSuc('ok');
    }

    public function rejectIncome()
    {
        $data = [
            'id' => $this->input_data['id'],
            'status' => 90
        ];
        db('VehicleIncomeExpense')->update($data);

        $this->resSuc('ok');
    }
    public function reject()
    {
        $data = [
            'id' => $this->input_data['id'],
            'reject_reason' => $this->post('reject_reason'),
            'status' => 90,
            'reject_user' => $this->user['realname'],
            'reject_user_id' => $this->user['id'],
            'reject_time' => time(),
        ];
        db('VehicleIncomeExpense')->update($data);

        $this->resSuc('ok');
    }

}
